package com.louis.kitty.admin.controller;


import com.louis.kitty.admin.util.FileTools;
import com.louis.kitty.admin.util.GlobalParams;
import com.louis.kitty.admin.util.HttpResultT;
import com.louis.kitty.admin.util.P;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Api(tags = "file")
@RestController
@RequestMapping("extend/file")
public class FileUploadController {
    @PostMapping("uploadFile")
    @ApiOperation("文件上传")
    HttpResultT<String> uploadFile(@RequestParam MultipartFile file) {
        HttpResultT<String> httpResultT = HttpResultT.create();
//        String fileName= String.valueOf(SnowFlakeUtil.getSnowFlakeId());
//        String path = GlobalParams.OTHER_FILE_UPLOAD_PATH + "/" + file.getOriginalFilename();
        String path = GlobalParams.OTHER_FILE_UPLOAD_PATH  + file.getOriginalFilename();
        File destFile = new File(path);
        try {
            // 不存在文件夹，创建文件夹
            if (destFile != null && !destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            file.transferTo(destFile);
        } catch (Exception e) {
            P.throwMessageIf(true, "上传文件至服务器失败");
        }
        return httpResultT.ok(path);
    }

    @PostMapping("deleteFile")
    @ApiOperation("删除文件")
    HttpResultT<String> deleteFile(@RequestParam String path) {
        HttpResultT<String> httpResultT = HttpResultT.create();
        final String urlDecoderString = FileTools.getURLDecoderString(path);
        File dest = new File(urlDecoderString);

        try {
            dest.delete();
        } catch (Exception e) {
            P.throwMessageIf(true, "删除文件的过程中发生错误");
        }
        return httpResultT.ok(path);
    }

    @GetMapping("downLoadFile")
    @ApiOperation("文件下载预览图片")
    void downLoadFile(@RequestParam(value = "path") String path, HttpServletResponse response, HttpServletRequest request) throws IOException {
        FileTools.downloadFiles(path, "file", response, request, true);
    }

    @GetMapping("downLoadFiles")
    @ApiOperation("文件excel")
    void downLoadFiles(@RequestParam(value = "path") String path, HttpServletResponse response, HttpServletRequest request) throws IOException {
        FileTools.downloadExcel(path, "file", response, request);
    }

    @GetMapping("downLoadFileView")
    @ApiOperation("文件下载")
    void downLoadFileView(@RequestParam(value = "path") String path, HttpServletResponse response, HttpServletRequest request) throws IOException {
        FileTools.downloadFiles(path, "file", response, request, false);
    }
}

